package com.sky.gateway.filter;

import com.sky.gateway.config.AuthProperties;
import com.sky.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private  AntPathMatcher antPathMatcher = new AntPathMatcher();
    private final JwtTool jwtTool;
    private final AuthProperties authProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1、获取Request对象
        ServerHttpRequest request = exchange.getRequest();
        // 2、判断路径是否需要拦截
        if (isExclude(request.getPath().toString()))
            return chain.filter(exchange);

        // 3、获取token
        List<String> token = request.getHeaders().get("token");
        Long userId = null;
        try {
            // 校验用户信息
            userId = jwtTool.parseToken(token.get(0));
        }catch (Exception e){
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        // 4、将用户信息存储
        String userInfo = String.valueOf(userId);
        ServerWebExchange serverWebExchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();

        // 5、放行
        return chain.filter(serverWebExchange);
    }

    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath,path))
                return true;
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
